/**
 * Copyright (c) 2012 Nokia Corporation.
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

import QtQuick 1.1
import QtWebKit 1.0
import "Login.js" as Login
import "Constants.js" as Constants

Item {
    id: loginView

    property string userToken: ""
    property string expTime: ""
    property bool authenticated: false
    property alias webViewProgress: webView.progress
    property alias webViewScale: webView.scale
    property alias reload: webView.reload

    signal loginCompleted(string token, int expTime)

    // Exposed WebView signals
    signal webViewLoadFinished()
    signal webViewLoadFailed()

    WebView {
        id: webView
        property string authUrl: constructUrl()

        /*!
          Constructs the URL of the authentication page.
        */
        function constructUrl()
        {
            var url = Constants.dialogUrl
                    + "&client_id=" + fbConnect.appId
                    + "&redirect_uri=" + Constants.redirectUrl
                    + "&response_type=token"
                    + "&display=" + Constants.screenType;

            if (fbConnect.permissions.length > 0) {
                url += "&scope=" + fbConnect.permissions.join();
            }

            return url;
        }

        anchors.fill: parent
        preferredWidth: parent.width
        preferredHeight: parent.height
        url: authUrl

        onLoadFailed: loginView.webViewLoadFailed();

        onLoadFinished: {
            userToken = Login.getToken(url.toString());
            expTime = Login.getParameter(url.toString(), "expires_in");

            if (userToken && expTime) {
                authenticated = true;
            }

            loginView.webViewLoadFinished();
        }
    }

    onAuthenticatedChanged: {
        fbConnect.accessToken = userToken;
        fbConnect.setExpirationTime(expTime);
        loginCompleted(userToken, expTime);
    }
}
